package com.SmartCare.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * druid监控平台配置
 */
@Configuration
public class DruidConfig {
    /*
        将自定义的Druid数据源添加到容器中，不再让Spring Boot自动创建
        绑定全局配置文件中的 druid 数据源属性到com.alibaba.druid.pool.DruidDataSource从而让它们生效
        @ConfigurationProperties(prefix = "spring.datasource")：作用就是将全局配置文件中
        前缀为 spring.datasource的属性值注入到com.alibaba.druid.pool.DruidDataSource 的同名参数中
    */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }

    //后台监控: web.xml ServletRegistrationBean
    //SpringBoot 内置 servlet容器，所以没有web.xml 替代方法：ServletRegistrationBean
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
        HashMap<String, String> initParameters = new HashMap<>();
        //增加配置 登录key
        initParameters.put("loginUsername","admin");
        initParameters.put("loginPassword","20231107");
        //允许谁都可以访问
        initParameters.put("allow","");
        //禁止访问 initParameters.put("xxx","192.168.11.23");
        bean.setInitParameters(initParameters);//设置初始化参数
        return bean;
    }
    //filter 过滤
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map<String, String> initParamenters = new HashMap<>();
        //配置不进行统计的内容
        initParamenters.put("exelusions","*.js,/druid/*");
        bean.setInitParameters(initParamenters);
        return bean;
    }

}
